# Importing Data
INDIA <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/UAE/India.xlsx")

# Checking the Imported Data
View(INDIA)

# Creating Time Series Data
INDIA_ts <- ts(INDIA, start=c(2007,04), end=c(2019,04), frequency=12)

# Viewing and Checking the Created Time Series Data
INDIA_ts
sum(is.na(INDIA_ts))
library(forecast)
INDIA_ts <- tsclean(INDIA_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(INDIA_ts)
plot(aggregate(INDIA_ts,FUN=mean))

# Decomposing
INDIA_ts_decomp <- decompose(INDIA_ts)
plot(INDIA_ts_decomp)

# Testing for Stationarity
acf(INDIA_ts, lag.max=20)
pacf(INDIA_ts, lag.max=20)

# To see any seasonal effect
boxplot(INDIA_ts~cycle(INDIA_ts))

# To remove trend effect
INDIA_ts_diff <- diff(INDIA_ts)
plot(INDIA_ts_diff)

# To remove variance effect
INDIA_ts_log <- log(INDIA_ts)
plot(INDIA_ts_log)

# To remove both (Trend and Variance) effects
INDIA_ts_both <- diff(log(INDIA_ts))
plot(INDIA_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(INDIA_ts, lag.max=20)
acf(log(INDIA_ts), lag.max=20)
acf(diff(INDIA_ts), lag.max=20)
acf(diff(log(INDIA_ts)), lag.max=20)
pacf(INDIA_ts, lag.max=20)
pacf(log(INDIA_ts), lag.max=20)
pacf(diff(INDIA_ts), lag.max=20)
pacf(diff(log(INDIA_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
INDIA_ts_model <- auto.arima(INDIA_ts)
INDIA_ts_model
INDIA_ts_model <- auto.arima(INDIA_ts, ic="aic", trace = TRUE)
INDIA_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(INDIA_ts_model$resid)
acf(INDIA_ts_model$residuals, main='ACF Residual')
pacf(INDIA_ts_model$residuals, main='ACF Residual')
Box.test(INDIA_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
INDIA_ts_forecast <- forecast (INDIA_ts_model, level=c(95), h=260)
plot(INDIA_ts_forecast)
INDIA_ts_forecast             


write.table(INDIA_ts_forecast, file="India_TSA.csv", sep=",")
